﻿@inject IStringLocalizer<TablesSearchTable> Localizer
@inject IStringLocalizer<Foo> FooLocalizer

<div>
    <Table TItem="Foo"
           IsPagination="true" PageItemsSource="@PageItemsSource"
           IsStriped="true" IsBordered="true"
           ShowToolbar="true" ShowSearch="true" IsMultipleSelect="true" ShowExtendButtons="true"
           AddModalTitle="@Localizer["AddModelTitle"]" EditModalTitle="@Localizer["EditModelTitle"]"
           SearchModel="@SearchModel" ShowEmpty="true" SearchMode="SearchMode.Top"
           OnQueryAsync="@OnSearchModelQueryAsync" OnResetSearchAsync="@OnResetSearchAsync"
           OnAddAsync="@OnAddAsync" OnSaveAsync="@OnSaveAsync" OnDeleteAsync="@OnDeleteAsync">
        <TableColumns>
            <TableColumn @bind-Field="@context.DateTime" Width="180" />
            <TableColumn @bind-Field="@context.Name" />
            <TableColumn @bind-Field="@context.Address" />
            <TableColumn @bind-Field="@context.Education" />
        </TableColumns>
        <SearchTemplate>
            <GroupBox Title="@Localizer["SearchTableGroupBoxText"]">
                <div class="row g-3 form-inline">
                    <div class="col-12 col-sm-6">
                        <BootstrapInput @bind-Value="@context.Name" PlaceHolder="@Localizer["NamePlaceholder"]" maxlength="50" ShowLabel="true" DisplayText="@FooLocalizer[nameof(context.Name)]" />
                    </div>
                    <div class="col-12 col-sm-6">
                        <BootstrapInput @bind-Value="@context.Address" PlaceHolder="@Localizer["AddressPlaceholder"]" maxlength="500" ShowLabel="true" DisplayText="@FooLocalizer[nameof(context.Address)]" />
                    </div>
                </div>
            </GroupBox>
        </SearchTemplate>
    </Table>
</div>

@code {
    /// <summary>
    /// Foo 类为Demo测试用，如有需要请自行下载源码查阅
    /// Foo class is used for Demo test, please download the source code if necessary
    /// https://gitee.com/LongbowEnterprise/BootstrapBlazor/blob/main/src/BootstrapBlazor.Shared/Data/Foo.cs
    /// </summary>
    [NotNull]
    private List<Foo>? Items { get; set; }

    private Foo SearchModel { get; set; } = new Foo();

    private static IEnumerable<int> PageItemsSource => new int[] { 4, 10, 20 };

    private IEnumerable<SelectedItem>? SearchItems { get; set; }

    /// <summary>
    /// OnInitialized 方法
    /// </summary>
    protected override void OnInitialized()
    {
        base.OnInitialized();

        Items = Foo.GenerateFoo(FooLocalizer);

        SearchItems = new List<SelectedItem>()
        {
            new SelectedItem { Text = Localizer["SelectedItemText"].Value, Value = "" },
            new SelectedItem { Text = Localizer["SelectedItemText1"].Value, Value = Localizer["SelectedItemValue1"].Value },
            new SelectedItem { Text = Localizer["SelectedItemText2"].Value, Value = Localizer["SelectedItemValue2"].Value },
        };
    }

    private static Task<Foo> OnAddAsync() => Task.FromResult(new Foo() { DateTime = DateTime.Now });

    private Task<bool> OnSaveAsync(Foo item, ItemChangedType changedType)
    {
        // 增加数据演示代码
        if (changedType == ItemChangedType.Add)
        {
            item.Id = Items.Max(i => i.Id) + 1;
            Items.Add(item);
        }
        else
        {
            var oldItem = Items.FirstOrDefault(i => i.Id == item.Id);
            if (oldItem != null)
            {
                oldItem.Name = item.Name;
                oldItem.Address = item.Address;
                oldItem.DateTime = item.DateTime;
                oldItem.Count = item.Count;
                oldItem.Complete = item.Complete;
                oldItem.Education = item.Education;
            }
        }
        return Task.FromResult(true);
    }

    private Task<bool> OnDeleteAsync(IEnumerable<Foo> items)
    {
        items.ToList().ForEach(i => Items.Remove(i));
        return Task.FromResult(true);
    }

    private static Task OnResetSearchAsync(Foo item)
    {
        item.Name = "";
        item.Address = "";
        return Task.CompletedTask;
    }

    private Task<QueryData<Foo>> OnSearchModelQueryAsync(QueryPageOptions options)
    {
        // 自定义了 SearchModel
        IEnumerable<Foo> items = Items;

        if (!string.IsNullOrEmpty(options.SearchText))
        {
            items = items.Where(i => (i.Name?.Contains(options.SearchText, StringComparison.OrdinalIgnoreCase) ?? false)
                || (i.Address?.Contains(options.SearchText, StringComparison.OrdinalIgnoreCase) ?? false));
        }
        else if (!string.IsNullOrEmpty(SearchModel.Name))
        {
            items = items.Where(i => i.Name == SearchModel.Name);
        }
        else if (!string.IsNullOrEmpty(SearchModel.Address))
        {
            items = items.Where(i => i.Address == SearchModel.Address);
        }

        // 设置记录总数
        var total = items.Count();

        // 内存分页
        items = items.Skip((options.PageIndex - 1) * options.PageItems).Take(options.PageItems).ToList();

        return Task.FromResult(new QueryData<Foo>()
        {
            Items = items,
            TotalCount = total,
            IsSorted = true,
            IsFiltered = true,
            IsSearch = true,
            IsAdvanceSearch = true
        });
    }

}
